import React, { Component } from 'react';
import { Modal, Select, Button, message } from 'antd';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { batchUpdateAssets } from '@api/asset';

class RemoveTagModal extends Component {
  constructor(props) {
    super(props);
    this.state = _.cloneDeep(RemoveTagModal.defaultProps);
  }

  static defaultProps = {
    tagName: '',
    tagId: '',
    stage: 'select'
  };

  static getDerivedStateFromProps(props) {
    if (!props.visible) {
      return _.cloneDeep(RemoveTagModal.defaultProps);
    }
  }

  static propTypes = {
    tags: PropTypes.array,
    siteIds: PropTypes.array,
    sites: PropTypes.array,
    loadAssets: PropTypes.func,
    visible: PropTypes.bool,
    onClose: PropTypes.func
  };

  onTagChange = (tagId, instance) => {
    let tagName = _.get(instance, 'props.children');
    this.setState({
      tagId,
      tagName
    });
  };

  onOk = () => {
    let { stage, tagId } = this.state;
    if (!tagId) {
      return;
    }
    if (stage === 'select') {
      this.setState({
        stage: 'confirm'
      });
    } else {
      // eslint-disable-next-line
      batchUpdateAssets({ query: { siteIds: this.props.siteIds }, pull: { tag_oids: [tagId] } })
        .then(() => {
          message.success('移除标签成功');
          this.props.onClose();
          this.props.loadAssets();
        })
        .catch(() => {
          message.error('移除标签失败');
        });
    }
  };

  render() {
    const { stage, tagName } = this.state;
    const { tags: rawTags = [], visible, onClose, sites = [] } = this.props;
    const siteTagIds = sites.reduce((total, current) => {
      return total.concat(_.get(current, 'tag_oids', []));
    }, []);
    const tags = rawTags.filter(({ _id }) => siteTagIds.includes(_id));
    const bottom = [
      <Button key={0} onClick={onClose}>
        取消
      </Button>,
      <Button type="danger" key={1} onClick={this.onOk}>
        {stage === 'select' ? '确定移除' : '确定'}
      </Button>
    ];
    return (
      <Modal
        maskClosable={false}
        width={300}
        visible={visible}
        title="移除标签"
        onCancel={onClose}
        className="padding-24 bottom-center no-header-bottom-lines"
        footer={bottom}
        destroyOnClose
      >
        {stage === 'select' ? (
          <Select
            placeholder={tags.length ? '选择标签' : '当前选中的资产无标签'}
            style={{ width: '100%' }}
            // value={[tagId]}
            onChange={this.onTagChange}
            allowClear
          >
            {tags.map(({ name, _id }) => (
              <Select.Option key={_id} value={_id}>
                {name}
              </Select.Option>
            ))}
          </Select>
        ) : (
          <div>确认移除&quot;{tagName}&quot;标签?</div>
        )}
      </Modal>
    );
  }
}

const mapStateToProps = state => {
  return {
    tags: _.get(state, 'tag.tags', [])
  };
};

export default connect(mapStateToProps)(RemoveTagModal);
